<?php
/**
 * 商品各类图片表
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/7
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Panx;

use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class ProductImage
 *
 * @property string|null key
 * @property int type
 *
 * @property-read string|null url - same as key to url
 *
 * @package App\Models\Panx
 * @mixin Builder
 */
class ProductImage extends Model
{
    use Bosable;

    protected $key_bos_key_prefix = 'product/thumb/';

    protected $table = 'product_images';

    protected $guarded = [];

    public $bos_columns = ['key'];

    protected $casts = [
        'type' => 'int',
    ];
    /**
     * 类型：缩略图
     */
    const TYPE_THUMB = 1;

    /**
     * 类型：颜色缩略图
     */
    const TYPE_COLOR_THUMB = 2;

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }

    /**
     * @param $key
     * @throws \Exception
     */
    public function setKeyAttribute($key)
    {
        if (is_file($key)) {
            $this->attributes['key'] = $this->uploadPostFile($key , $this->key_bos_key_prefix);
        }else{
            $this->attributes['key'] = $key;
        }

    }

    /**
     * @return mixed|null
     */
    public function getKeyAttribute()
    {
        if (! $this->attributes['key']) return null;

        return $this->getStaticUrl($this->attributes['key']);
    }

    /**
     * @used-by $url
     *
     * @return mixed|null
     */
    public function getUrlAttribute()
    {
        return $this->key;
    }

    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();

        /**
         * 监听bos清理事件
         *
         * @link https://coding.net/u/zeon/p/beauty-mirror/task/3803123 - #656 模型组要求不清理
         */
//        self::observe(BosCleanObserver::class);
    }
}
